package org.jeecg.modules.compilation.service.impl;
import org.jeecg.modules.compilation.entity.*;
import org.jeecg.modules.compilation.mapper.CiFavoriteMapper;
import org.jeecg.modules.compilation.mapper.CiNoteMapper;
import org.jeecg.modules.compilation.service.*;
import org.jeecg.modules.compilation.vo.AnnexFileVO;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.util.CollectionUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.xcontent.XContentType;
import org.jeecg.common.es.JeecgElasticsearchTemplate;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.compilation.dto.*;
import org.jeecg.modules.compilation.mapper.CiDocMapper;
import org.jeecg.modules.compilation.transfer.DocumentTransfer;
import org.jeecg.modules.compilation.util.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

import java.text.ParseException;
import java.util.*;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
 * @Description: ci_doc
 * @Author: jeecg-boot
 * @Date: 2024-03-15
 * @Version: V1.0
 */
@Service
@Slf4j
public class CiDocServiceImpl extends ServiceImpl<CiDocMapper, CiDoc> implements ICiDocService {

    @Autowired
    private CiFavoriteMapper ciFavoriteMapper;
    @Autowired
    private CiNoteMapper ciNoteMapper;
    @Autowired
    private CommonUtil commonUtil;
    @Autowired
    private JeecgElasticsearchTemplate jeecgElasticsearchTemplate;
    @Autowired
    private CiDocMapper ciDocMapper;
    private CiDoc ciDoc;
    @Autowired
    private MinioService minioService;
    @Value("${minio.url}")
    private String previewUrl;
    @Autowired
    private MinioUtil minioUtil;
    @Autowired
    private ICiBusinessCategoryService ciBusinessCategoryService;
    @Autowired
    private ICiSysUserService sysUserService;

    @Override
    public List<CiDocDTO> list(String businessCategorySn) {
        List<CiDoc> ciDocs = ciDocMapper.List(businessCategorySn);
        List<CiDocDTO> ciDocDTOs = new ArrayList<>();
        //BeanUtils.copyProperties(ciDocs,ciDocDTOs);
        for (CiDoc ciDoc : ciDocs) {
            CiDocDTO ciDocDTO = new CiDocDTO();
            BeanUtils.copyProperties(ciDoc, ciDocDTO);
            // 将 CiDocDTO 对象添加到 List 中
            ciDocDTOs.add(ciDocDTO);
        }
        return ciDocDTOs;
    }

    @Override
    public CiDocDTO getDoc(String documentSn) {
        CiDocDTO ciDocDTO = new CiDocDTO();
        ciDoc = ciDocMapper.getDoc(documentSn);
        BeanUtils.copyProperties(ciDoc, ciDocDTO);
        return ciDocDTO;
    }

    @Autowired
    private JeecgElasticsearchTemplate elasticsearchTemplate;

    /*
     * 文件内容全文检索
     * */
    @Override
    public List<CiDoc> search(SearchFileDTO searchFileDTO) throws IOException {
        RestHighLevelClient restHighLevelClient = elasticsearchTemplate.elasticsearchClient();
        SearchRequest request = new SearchRequest("document");
        String key = searchFileDTO.getKeyword();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//        boolQuery.must(QueryBuilders.matchQuery("documentSn", searchFileDTO.getDocumentSn()));
        boolQuery.must(QueryBuilders.matchQuery("documentSn", searchFileDTO.getDocumentSn()));
        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchQuery("htmlText", ""));
        } else {
            boolQuery.must(QueryBuilders.matchPhraseQuery("htmlText", key));
        }
//        boolQuery.must(QueryBuilders.matchQuery("documentSn", searchFileDTO.getDocumentSn()));
        request.source().query(boolQuery);
        request.source().highlighter(new HighlightBuilder().field("htmlText").requireFieldMatch(true));
        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        long value = hits.getTotalHits().value;
        System.out.println(value + "条数据");
        System.out.println("-------------------------------------");
        SearchHit[] hits1 = hits.getHits();
        int i = 0;
        List<CiDoc> list = new ArrayList<>();
        for (SearchHit hit : hits1) {
            String json = hit.getSourceAsString();
            CiDoc ciDoc = JSON.parseObject(json, CiDoc.class);
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            String originalText = ciDoc.getHtmlText(); // 获取原始的htmlText
            if (!CollectionUtils.isEmpty(highlightFields)) {
                HighlightField highlight = highlightFields.get("htmlText");
                if (highlight != null) {
                    Text[] fragments = highlight.getFragments();
                    String highlightedText = Arrays.stream(fragments)
                            .map(Text::string)
                            .collect(Collectors.joining());
                    i++;
                    // 将高亮文本插入到原始文本中
                    String combinedText = insertHighlights(originalText, key, highlightedText);
                    ciDoc.setHtmlText(combinedText);
                }
            }
            list.add(ciDoc);
        }
        return list;
    }


    //    /*
//   *  解析请求
//    */
    private List<AiDocWebQueryDTO> handleResponse(SearchResponse search) {
        SearchHits hits = search.getHits();
        long value = hits.getTotalHits().value;
        System.out.println(value + "条数据");
        System.out.println("-------------------------------------");
        SearchHit[] hits1 = hits.getHits();
        List<AiDocWebQueryDTO> list = new ArrayList<>();
        for (SearchHit hit : hits1) {
            String josn = hit.getSourceAsString();
            AiDocWebQueryDTO aiDocWebQueryDTO = JSON.parseObject(josn, AiDocWebQueryDTO.class);
            list.add(aiDocWebQueryDTO);
        }
        return list;
    }

    private String insertHighlights(String originalText, String searchKeyword, String highlightedText) {
        // 使用正则表达式构建搜索关键词的模式，考虑到关键词可能包含正则表达式的特殊字符
        String regex = Pattern.quote(searchKeyword);
        // 创建一个正则表达式模式，用于匹配关键词
        Pattern pattern = Pattern.compile(regex);
        // 创建一个匹配器，用于在原始文本中查找关键词
        Matcher matcher = pattern.matcher(originalText);

        // 使用高亮文本替换所有匹配的关键词
        String resultText = matcher.replaceAll(highlightedText);

        return resultText;
    }

    /*
     * rabbit监听的删除方法
     * */
    @Override
    public void deleteById(Long id) {
        try {
            RestHighLevelClient client = elasticsearchTemplate.elasticsearchClient();
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("document", id.toString());

            // 2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /*
     * rabbit监听的更新和添加方法
     * */
    @Override
    public void insertById(Long id) throws IOException {
        RestHighLevelClient restHighLevelClient = elasticsearchTemplate.elasticsearchClient();
        CiDoc ciDoc = this.getById(id);
        IndexRequest request = new IndexRequest("document").id(ciDoc.getId().toString());
        request.source(JSON.toJSONString(ciDoc), XContentType.JSON);
        restHighLevelClient.index(request, RequestOptions.DEFAULT);

    }

    @Override
    public void deleteBatch(List<String> list) {
        try {
            RestHighLevelClient client = elasticsearchTemplate.elasticsearchClient();
            for (String id : list) {
                // 1.准备Request
                DeleteRequest request = new DeleteRequest("document", id);
                // 2.发送请求
                client.delete(request, RequestOptions.DEFAULT);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<SearchcIDocDraftDTO> searchList(String documentTitle) throws IOException {
        RestHighLevelClient restHighLevelClient = elasticsearchTemplate.elasticsearchClient();
        SearchRequest request = new SearchRequest("document");

        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (documentTitle != null && !"".equals(documentTitle)) {
            boolQuery.must(QueryBuilders.matchPhraseQuery("documentTitle", documentTitle));
        }
        request.source().query(boolQuery);
        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        long value = hits.getTotalHits().value;
        System.out.println(value + "条数据");
        System.out.println("-------------------------------------");
        SearchHit[] hits1 = hits.getHits();
        List<SearchcIDocDraftDTO> list = new ArrayList<>();
        for (SearchHit hit : hits1) {
            String josn = hit.getSourceAsString();
            SearchcIDocDraftDTO aiDocWebQueryDTO = JSON.parseObject(josn, SearchcIDocDraftDTO.class);
            list.add(aiDocWebQueryDTO);
        }
        restHighLevelClient.close();
        return list;
    }

    @Override
    public String previewProcessingInterface(MultipartFile preView) throws Exception {

        String user = "preview-";

        String tmp = UUID.randomUUID().toString().substring(0, 6);
        //上传文件名称
        String oldName = preView.getOriginalFilename();
        //文件新名称
        String pre = Constants.CURRENT_SEPARATOR + "html" + Constants.CURRENT_SEPARATOR + "preview" + Constants.CURRENT_SEPARATOR;
        String fileName = pre + tmp + oldName.substring(oldName.lastIndexOf("."));
        String path = FolderUtil.setAbsolutePath(fileName);
        log.info("文件正在写入，保存doc路径:{}", path);
        File dest = new File(path);
        if(!dest.exists()){
            dest.mkdirs();
        }
        // 文件写入

        //todo
//        String absolutePath = dest.getAbsolutePath();
//        preView.transferTo(Paths.get(absolutePath));
        //todo
        preView.transferTo(dest);

        //todo
//        String name = absolutePath.replace(absolutePath.substring(absolutePath.lastIndexOf(".")), ".pdf");
        //todo
        String name = path.replace(path.substring(path.lastIndexOf(".")), ".pdf");

        log.info("开始转成pdf，保存pdf路径:{}", name);
//        LibreOfficeUtil.wordConverterToPdf( path , name );
//        openofficeUtil.convertFileToPdf(path, name);
//        Integer start = name.lastIndexOf("/") + 1;

        //todo
//        AsposeUtil.ToPDF(absolutePath, name);
        //todo
        AsposeUtil.ToPDF(path, name);

//        name = name.substring(sta)

        String pdfPath = name.replace(tmp, user + tmp);
        log.info("pdf开始+水印，保存路径:{}", pdfPath);

        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //加水印
        PdfUtils.addwaterMark(
                loginUser.getRealname(),
                name, pdfPath,
                0.30f,
                12,
                50,
                1,
                3,
                false
        );

        //从linux获取文件保存到minio上
//        String filename = getLinuxDoc(pdfPath);
//        return previewUrl + filename;


        //写入minio上
        InputStream inputStream = new FileInputStream(new File(pdfPath));
        String objectName = pdfPath.substring(pdfPath.lastIndexOf("\\") + 1);
//        String[] previews = pdfPath.split("preview", 1);
//        String objectName = pdfPath.split("preview",1)[1].substring(1);
        minioUtil.uploadFile(inputStream,"compilation-institutions",objectName);
        return previewUrl + "/"+"compilation-institutions"+"/"+objectName;
//        return null;
    }

    /**
     * 自定义代码
     */
    public String getLinuxDoc(String path) {
        String filename = path.substring(path.lastIndexOf("\\") + 1);
        String filepath = path.substring(0,path.lastIndexOf("\\"));
        // 创建SSH连接
        JSch jsch = new JSch();
        Session session = null;
        try {
            session = jsch.getSession("root", "101.33.213.227", 22);
            session.setPassword("JavaEE2024!");
            session.connect();
            // 创建SFTP通道
            ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
            channel.connect();
            // 定位到文件路径
            channel.cd(filepath);
            // 读取文件内容
            InputStream inputStream = channel.get(filename);
            minioUtil.uploadFile(inputStream,"compilation-institutions",filename);
//// 使用BufferedReader读取文件内容
//            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
//            String line;
//            while ((line = reader.readLine()) != null) {
//                System.out.println(line);
//            }
//            reader.close();
            inputStream.close();
            channel.disconnect();
            session.disconnect();
        } catch (JSchException e) {
            throw new RuntimeException("linux服务器连接失败");
        } catch (SftpException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return filename;
    }
    @Override
    public Boolean save(CiDocEditOrUpdateDTO dto, MultipartFile docFile, MultipartFile[] annexFiles) throws Exception {
        if (docFile.getOriginalFilename() == null || docFile.getOriginalFilename().equals(""))
            throw new RuntimeException("制度文件上传名字不能为空！");
        if (annexFiles != null) {
            for (MultipartFile multipartFile : annexFiles)
                if (multipartFile.getOriginalFilename() == null || multipartFile.getOriginalFilename().equals(""))
                    throw new RuntimeException("上传附件名字不能为空！");
        }

        CiDoc doc = new CiDoc();
        BeanUtils.copyProperties(dto,doc);

        //生成编号
        doc.setDocumentSn(CommonUtil.getSn()).setIsAnnex("0");
        //处理制度文件
        this.handleDocFile(doc, dto, docFile, true);
        doc.setBusinessCategoryUrl(
                ciBusinessCategoryService
                        .lambdaQuery()
                        .eq(CiBusinessCategory::getBusinessCategorySn, dto.getBusinessCategorySn())
                        .one()
                        .getBusinessCategoryUrl()
        );

        try {
            this.save(doc);
            //处理附件
            if (annexFiles != null) {
                this.hanleAnnexFiles(doc, dto, annexFiles);
            }
        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Override
    public String previewCi(String documentSn) throws Exception {

        CiDoc ciDoc = this.lambdaQuery().eq(CiDoc::getDocumentSn, documentSn).one();
        if (ciDoc == null || !StrUtil.isNotBlank(ciDoc.getPdfRoute()) || !StrUtil.isNotBlank(ciDoc.getRealRoute())) {
            throw new RuntimeException("文件不存在！");
        }
        String pdfPath = ciDoc.getPdfRoute();
        String path = pdfPath.substring(pdfPath.substring(0, pdfPath.lastIndexOf("/")).lastIndexOf("/") + 1);
        log.info("文件预览开始..........，获取的文件名称为{},文件路径为 {}", ciDoc.getPdfRoute().substring(ciDoc.getPdfRoute().lastIndexOf("/")), previewUrl + path);
        String rand = UUID.randomUUID().toString().substring(0, 6);
        //获取登录用户信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = loginUser.getId();
        String userPath = Constants.HOME_FOLDER_NAME + "temp" + Constants.HOME_FOLDER_NAME + userId + Constants.CURRENT_SEPARATOR;
        String userAbsolutePath = FolderUtil.setAbsolutePath(userPath);
        FolderUtil.createFolder(userAbsolutePath);
        userAbsolutePath = userAbsolutePath + rand + ".pdf";
        log.info("添加水印文件位置：{}", userAbsolutePath);
        //加水印
        PdfUtils.addwaterMark(
                loginUser.getRealname(),
                pdfPath, userAbsolutePath,
                0.30f,
                12,
                50,
                1,
                3,
                false
        );
        //将文件保存到minio中
        InputStream inputStream = new FileInputStream(new File(userAbsolutePath));
        String substring = userAbsolutePath.substring(userAbsolutePath.lastIndexOf("\\") + 1);
        minioUtil.uploadFile(inputStream,"compilation-institutions",substring);

        log.info("nginx映射位置：{}", previewUrl + Constants.CURRENT_SEPARATOR + "compilation-institutions"+Constants.CURRENT_SEPARATOR+substring);
        return previewUrl + Constants.CURRENT_SEPARATOR + "compilation-institutions"+Constants.CURRENT_SEPARATOR+substring;
    }

    public void handleDocFile(CiDoc doc, CiDocEditOrUpdateDTO dto, MultipartFile file, Boolean isES) throws Exception {
        //保存word路径
        doc.setRealRoute(handleFile(dto, file, 1));
        log.info("处理数据信息展示：{}", doc);
        //进行html内容和样式解析
        new HtmlToString().handleToHtml(doc, file);
//        保存pdf路径
//        String [] tmp  = handleWordToPdf(dto.getBusinessCategoryName(), doc.getRealRoute()).split("-");
//        if ( tmp.length == 0 )
//            throw new JeecgBootBusinessException("pdf转页失败！");
//        doc.setPdfRoute( tmp[0] ).setPdfPages( Integer.parseInt( tmp[1] ) );
        doc.setPdfRoute(handleWordToPdf(dto.getBusinessCategoryName(), doc.getRealRoute()));
        //读取正文
        doc.setContent(WordUtil.handleWordContent(doc.getRealRoute()));
        //设置pdf页数
        doc.setPdfPages(PdfUtils.getPdfNum(doc.getPdfRoute()));
        //存储进ES
        if (isES)
            saveToES(doc);
    }
    public void saveToES(CiDoc dto) throws IOException {
        //获取ES客户端
        RestHighLevelClient esClient = jeecgElasticsearchTemplate.elasticsearchClient();
        Document document = DocumentTransfer.INSTANCE.toEntity(dto);
        document.setEnableFlag("1");

        IndexRequest request = new IndexRequest();
        request.index("document").id(dto.getDocumentSn());
        log.info("ES存储开始，ES存储索引名称{}，ES存储id为{}", "document", dto.getDocumentSn());

        //向es插入数据，必须将数据转成json格式
        ObjectMapper mapper = new ObjectMapper();
        String documentJson = mapper.writeValueAsString(document);
        request.source(documentJson, XContentType.JSON);
        log.info("ES创建文档传入值：{}", documentJson);
        IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
        log.info("ES返回值：{}", response.getResult());

        //关闭ES客户端

        esClient.close();
    }
    private void hanleAnnexFiles(CiDoc doc, CiDocEditOrUpdateDTO dto, MultipartFile[] annexFiles) throws IOException, ParseException {
        log.info("上传附件个数：{}", annexFiles.length);
        for (MultipartFile file : annexFiles) {
            log.info("文件名称为：{}", file.getOriginalFilename());
        }
        //处理附件
        for (MultipartFile annexFile : annexFiles) {
            CiDoc annexDoc = new CiDoc();
            BeanUtils.copyProperties(dto,annexDoc);

            Random random = new Random();
            int randomNum = random.nextInt(900) + 100;

            annexDoc.setId("")
                    .setIsAnnex("1")
                    .setDocumentIdentifier(doc.getDocumentIdentifier() + "附件-" + randomNum)
                    .setDocumentSn(CommonUtil.getSn())
                    .setDocumentTypeName("附件")
                    .setBusinessCategoryName("附件");
            annexDoc.setDocumentTitle(
                    annexFile.getOriginalFilename()
                            .substring(
                                    0,
                                    annexFile.getOriginalFilename().lastIndexOf(".")
                            ));
            //附件存储路径
            annexDoc.setRealRoute(handleFile(dto, annexFile, 0));
            log.info("附件真实存储路径：{}", annexDoc.getRealRoute());
            annexDoc.setPdfRoute(handleWordToPdf(dto.getBusinessCategoryName(), annexDoc.getRealRoute()));
            log.info("附件真实存储路径：{}", annexDoc.getPdfRoute());
            annexDoc.setParentDocSn(doc.getDocumentSn());
            //保存附件信息
            this.save(annexDoc);
        }
    }
    /***
     *
     * @return 返回文件存放路径
     *
     * isRealName 0 保持文件原名 1 改文件名称为字号
     *
     * */
    public String handleFile(CiDocEditOrUpdateDTO dto, MultipartFile file, Integer isRealName) throws IOException {

        //上传文件名称
        String oldName = file.getOriginalFilename();
        //文件新名称
        String fileName = isRealName == 1 ? dto.getDocumentIdentifier() + oldName.substring(oldName.lastIndexOf(".")) : oldName;
        //文件后缀
//        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1).equals("doc") ? "doc" : "docx";
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        log.info("后缀：{}", suffix);
        fileName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + suffix;
        //文件主目录(AssemblyOfRegulations) + 二级目录(业务类型)
        String filePath = Constants.HOME_FOLDER_NAME + dto.getBusinessCategoryName() + Constants.CURRENT_SEPARATOR;
        //文件临时主目录(temp) + 二级目录(业务类型)
        String tempPath = Constants.HOME_FOLDER_NAME + "temp" + Constants.CURRENT_SEPARATOR;
        //生成当前运行位置(适配linux和win) + 文件主目录(AssemblyOfRegulations) + 二级目录(业务类型)
        String absolutePath = FolderUtil.setAbsolutePath(filePath);
        String tempabsolutePath = FolderUtil.setAbsolutePath(tempPath);
        //创建文件夹
        FolderUtil.createFolder(absolutePath);
        FolderUtil.createFolder(tempabsolutePath);
        //文件路径
        String path = absolutePath + fileName;
        File dest = new File(path);

        //todo
//        String destAbsolutePath = dest.getAbsolutePath();
//        file.transferTo(Paths.get(destAbsolutePath));
        //todo
        // 文件写入
        file.transferTo(dest);

        //上传文件日志信息查看
        log.info("=vvvvv=====原文件信息===vvvvv==");
        log.info("文件类型ContentType：{}", file.getContentType());
        log.info("文件组件名称Name：{}", file.getName());
        log.info("文件原名称OriginalFileName:{}", file.getOriginalFilename());
        log.info("文件大小Size：{}", file.getSize() / 1024 + "KB");
        log.info("=^^^^^=====原文件信息===^^^^^==");
        log.info("=vvvvv=====上传文件信息===vvvvv==");
        log.info("文件名称：{}", fileName);
        log.info("文件目录路径：{}", filePath);
        log.info("生成文件文件位置：{}", path);
        log.info("=^^^^^=====上传文件信息===^^^^^==");

        return path;
    }
    private String handleWordToPdf(String businessCategoryName, String wordPath) {
        try {
            String name = wordPath
                    .replace(businessCategoryName, "temp")
                    .replace(wordPath.substring(wordPath.lastIndexOf(".")), ".pdf");
//            openofficeUtil.convertFileToPdf(wordPath, name);
            AsposeUtil.ToPDF(wordPath, name);
            log.info("==vvvvv==word转换成pdf==vvvvv==");
            log.info("原word文件路径：{}", wordPath);
            log.info("生成pdf文件路径：{}", name);
            log.info("==^^^^^==word转换成pdf==^^^^^==");
            return name;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    @Override
    public Boolean edit(CiDocEditOrUpdateDTO dto, MultipartFile file, MultipartFile[] annexFiles) throws Exception {

        if (!StrUtil.isNotBlank(dto.getDocumentSn())) {
            throw new JeecgBootException("缺少documentSn!");
        }
        List<String> queryAnnex = this.lambdaQuery()
                .eq(CiDoc::getParentDocSn, dto.getDocumentSn())
                .list()
                .stream()
                .map(CiDoc::getDocumentSn)
                .collect(Collectors.toList());

        log.info("该制度文件本身拥有的附件为：{}", queryAnnex);


        if (queryAnnex.size() != 0) {
            this.lambdaUpdate().in(CiDoc::getDocumentSn, queryAnnex).set(CiDoc::getParentDocSn, "").update();
        }

        try {
            if (dto.getAnnexFiles() != null && dto.getAnnexFiles().size() != 0) {
                List<String> changeAnnexList = dto.getAnnexFiles().stream().map(AnnexFileVO::getDocumentSn).collect(Collectors.toList());
                List<String> remList = queryAnnex.stream().filter(data -> !changeAnnexList.contains(data)).collect(Collectors.toList());
                log.info("需要进行删除的附件：{}", remList);
                if (remList.size() != 0) {
                    this.remove(new LambdaQueryWrapper<CiDoc>().in(CiDoc::getDocumentSn, remList));
                }
                log.info("应修改的附件为：{}", dto.getAnnexFiles().stream().map(AnnexFileVO::getDocumentSn).collect(Collectors.toList()));
                this.lambdaUpdate()
                        .in(CiDoc::getDocumentSn, changeAnnexList)
                        .set(CiDoc::getParentDocSn, dto.getDocumentSn()).update();
            }
        } catch (Exception e) {
            log.info("更改已存在数据类型。");
        }

        if (annexFiles != null) {
            this.hanleAnnexFiles(
                    new CiDoc().setDocumentSn(dto.getDocumentSn()),
                    dto,
                    annexFiles);
        }

        //shi上逻辑，千万别动，牵扯太多地方了
        CiDoc realDoc = this.lambdaQuery().eq(CiDoc::getDocumentSn, dto.getDocumentSn()).one();
        int flag = 0;
        if (realDoc.getEnableFlag().equals("0") && dto.getEnableFlag().equals("1")) {
            flag = 1;
        }

        CiDoc doc = new CiDoc();
        BeanUtils.copyProperties(dto,doc);
        if (file != null) {
            CiDoc tem = this.lambdaQuery().eq(CiDoc::getDocumentSn, dto.getDocumentSn()).one();
            FolderUtil.delFile(new File(tem.getRealRoute()));
            FolderUtil.delFile(new File(tem.getPdfRoute()));
            handleDocFile(doc, dto, file, true);
        }

        if (flag == 1) {
            doc.setAbolitionDate(null);
            this.lambdaUpdate()
                    .eq(CiDoc::getDocumentSn, doc.getDocumentSn())
                    .set(CiDoc::getAbolitionDate, null)
                    .update();
        }

        return this.updateById(doc);
    }
    @Override
    public Boolean removeBySn(String documentSn) {
//        Boolean note = ciNoteService.lambdaUpdate().set(CiNote::getEnableFlag, "0").eq(CiNote::getDocumentSn, documentSn).update();
        LambdaQueryWrapper<CiNote> ciNoteLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ciNoteLambdaQueryWrapper.eq(CiNote::getDocumentSn, documentSn);
        CiNote ciNote = ciNoteMapper.selectOne(ciNoteLambdaQueryWrapper);
        if(ciNote!=null) {
            ciNote.setEnableFlag("0");
            ciNoteMapper.updateById(ciNote);
            log.info("笔记状态更改情况：{}", ciNote);
        }
//        Boolean favor = ciFavoriteService.lambdaUpdate().set(CiFavorite::getEnableFlag, "0").eq(CiFavorite::getDocumentSn, documentSn).update();
        LambdaQueryWrapper<CiFavorite> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CiFavorite::getDocumentSn, documentSn);
        CiFavorite ciFavorite = ciFavoriteMapper.selectOne(lambdaQueryWrapper);
        if(ciFavorite!=null) {
            ciFavorite.setEnableFlag("0");
            ciFavoriteMapper.updateById(ciFavorite);
            log.info("收藏夹状态更改情况：{}", ciFavorite);
        }
        this.remove(new LambdaQueryWrapper<CiDoc>().eq(CiDoc::getParentDocSn, documentSn));
        return this.remove(new LambdaQueryWrapper<CiDoc>().eq(CiDoc::getDocumentSn, documentSn));
    }
}
